// internal/middleware/security.go
package middleware

import (
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

func SecurityMiddleware() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		// 设置安全相关的HTTP头
		ctx.Header("X-Content-Type-Options", "nosniff")
		ctx.Header("X-Frame-Options", "DENY")
		ctx.Header("X-XSS-Protection", "1; mode=block")
		ctx.Header("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
		
		// 防止MIME类型嗅探
		ctx.Header("X-Content-Type-Options", "nosniff")
		
		// 防止点击劫持
		ctx.Header("X-Frame-Options", "DENY")
		
		// 移除服务器信息
		ctx.Header("Server", "JFastFiler")
		
		// 检查Content-Type
		if ctx.Request.Method == "POST" || ctx.Request.Method == "PUT" {
			contentType := ctx.Request.Header.Get("Content-Type")
			if !strings.HasPrefix(contentType, "application/json") && 
			   !strings.HasPrefix(contentType, "multipart/form-data") &&
			   !strings.HasPrefix(contentType, "application/x-www-form-urlencoded") {
				ctx.JSON(http.StatusUnsupportedMediaType, gin.H{"error": "不支持的Content-Type"})
				ctx.Abort()
				return
			}
		}
		
		ctx.Next()
	}
}